<script setup lang="ts">
import { RouterView } from 'vue-router';
import { useSettingsStore } from '@/stores/settings';
import { onMounted, watch, ref } from 'vue';

const settingsStore = useSettingsStore();
const isReady = ref(false); // 新增：最终的“就绪”状态，控制淡入动画

// A utility to convert hex to rgb
const hexToRgb = (hex: string) => {
  if (!hex) return null;
  const result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
  return result
    ? {
        r: parseInt(result[1], 16),
        g: parseInt(result[2], 16),
        b: parseInt(result[3], 16),
      }
    : null;
};

// 最终的、事件驱动的、绝对健壮的加载和应用逻辑
const loadAndApplyTheme = (state: any) => {
  const root = document.documentElement;
  const body = document.body;

  // --- 立即应用非图片设置 ---
  document.title = state.siteTitle;
  let favicon = document.querySelector("link[rel~='icon']") as HTMLLinkElement;
  if (!favicon) {
    favicon = document.createElement('link');
    favicon.rel = 'icon';
    document.getElementsByTagName('head')[0].appendChild(favicon);
  }
  favicon.href = state.faviconUrl;

  root.style.setProperty('--color-text', state.fontColor);
  root.style.setProperty('--color-heading', state.fontColor);

  if (state.darkMode) {
    body.classList.add('dark-mode');
  } else {
    body.classList.remove('dark-mode');
  }
  
  const bgImageLayer = document.getElementById('app-background-image');
  const bgBlurLayer = document.getElementById('app-backdrop-blur');

  if (bgImageLayer && bgBlurLayer) {
    const rgb = hexToRgb(state.backgroundColor);
    if (rgb) {
      bgBlurLayer.style.backgroundColor = `rgba(${rgb.r}, ${rgb.g}, ${rgb.b}, ${state.backgroundColorOpacity})`;
    }
    bgBlurLayer.style.backdropFilter = `blur(${state.blurIntensity}px)`;
    (bgBlurLayer.style as any).webkitBackdropFilter = `blur(${state.blurIntensity}px)`;
  }

  // --- 关键：处理背景图片的预加载（已修复缓存BUG） ---
  // --- 增强的背景图片处理逻辑 ---
  const imageUrl = state.backgroundImage?.trim();
  const maxRetries = 3;
  let retryCount = 0;

  const loadImage = () => {
    if (!imageUrl) {
      // 无背景图片或空URL：清除背景并继续
      if (bgImageLayer) {
        bgImageLayer.style.backgroundImage = 'none';
      }
      isReady.value = true;
      return;
    }

    const img = new Image();
    
    const onImageLoad = () => {
      if (bgImageLayer) {
        bgImageLayer.style.backgroundImage = `url(${imageUrl})`;
      }
      isReady.value = true;
    };

    const onImageError = () => {
      console.error(`Failed to load background image (attempt ${retryCount + 1}/${maxRetries}):`, imageUrl);
      
      if (retryCount < maxRetries) {
        retryCount++;
        setTimeout(loadImage, 1000 * retryCount); // 递增延迟重试
      } else {
        // 所有重试都失败：清除背景并继续
        if (bgImageLayer) {
          bgImageLayer.style.backgroundImage = 'none';
        }
        isReady.value = true;
      }
    };

    img.onload = onImageLoad;
    img.onerror = onImageError;

    // 添加时间戳以避免缓存问题
    const urlWithCache = imageUrl.includes('?')
      ? `${imageUrl}&_t=${Date.now()}`
      : `${imageUrl}?_t=${Date.now()}`;
    
    img.src = urlWithCache;

    if (img.complete) {
      onImageLoad();
    }
  };

  // 启动图片加载流程
  loadImage();
};

onMounted(() => {
  // 关键修复：
  // 1. 立即从本地存储加载，瞬时恢复主题
  settingsStore.loadSettingsFromLocalStorage();
  
  // 2. 立即应用已加载的主题，消除闪烁
  loadAndApplyTheme(settingsStore.$state);

  // 3. 在后台异步获取最新设置
  settingsStore.fetchSettings();
});

// 监视后续的设置变更
watch(
  () => settingsStore.$state,
  (newState, oldState) => {
    // 仅在状态实际变化时才重新加载，避免不必要的计算
    if (JSON.stringify(newState) !== JSON.stringify(oldState)) {
      loadAndApplyTheme(newState);
    }
  },
  { deep: true }
);
</script>

<template>
  <div id="app-background-image"></div>
  <div id="app-backdrop-blur"></div>
  <div id="app-content" :class="{ 'app-loading': !isReady }">
    <RouterView />
  </div>
</template>

<style>
/* The conflicting @import of main.css has been REMOVED. This is a critical part of the fix. */
/* The single source of truth for static CSS is now main.ts. */

/* Import a dark theme for highlight.js */
@import 'highlight.js/styles/atom-one-dark.css';

#app-background-image {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  z-index: -2;
  background-size: cover;
  background-position: center;
  background-repeat: no-repeat;
  transition: background-image 0.3s;
}

#app-backdrop-blur {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  z-index: -1;
  transition: background-color 0.3s;
}

#app-content {
  position: relative;
  z-index: 1;
  min-height: 100vh;
  opacity: 1;
  transition: opacity 0.4s ease-in-out;
}

#app-content.app-loading {
  opacity: 0;
}
</style>
